package com.tr.rentcar.common.filter;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.tr.rentcar.model.bean.User;
import com.tr.rentcar.model.dao.UserDao;

/**
 * Servlet Filter implementation class Loginfilter
 * 登录过滤
 */
@WebFilter(dispatcherTypes = { DispatcherType.REQUEST, DispatcherType.FORWARD }, urlPatterns = { "/*" })
public class AutoLoginfilter implements Filter {

	/**
	 * Default constructor.
	 */
	public AutoLoginfilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpSession session = request.getSession();
		//如果已经登录了可以直接放行
		if (request.getSession().getAttribute("userinfo") != null) {
			chain.doFilter(req, resp);
			return;
		}else{
			//获取cookie
			String value=null;
			Cookie [] cookies=request.getCookies();
			for(int i=0;cookies!=null && i<cookies.length;i++){
				if(cookies[i].getName().equals("autologin")){
					value=cookies[i].getValue();
				}
			}
			if(value!=null){
				try {
					String phonenumber=value.split("\\.")[0];
					String password=value.split("\\.")[1];
					//检查用户电话和密码是否正确
					User user=new UserDao().findByTel(phonenumber);
					String dbpassword=user.getUpassword();
					
					if(password.equals(dbpassword)){
						session.setAttribute("userinfo", user);
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		chain.doFilter(req, resp);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		//System.out.println("进来login过滤器了");
	}

}
